<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  devices: {
    type: Array,
    required: true
  }
})

// 图表实例
let deviceRankingChart = null

// 引用
const deviceRankingRef = ref(null)

// 初始化设备排名图
const initDeviceRanking = () => {
  if (deviceRankingChart) {
    deviceRankingChart.dispose()
  }
  
  deviceRankingChart = echarts.init(deviceRankingRef.value)
  
  // 按功率排序后取前五
  const topDevices = [...props.devices]
    .sort((a, b) => b.power - a.power)
    .slice(0, 5);
    
  const option = {
    backgroundColor: 'transparent',
    grid: {
      left: '10%',
      right: '5%',
      top: '10%',
      bottom: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 10
      }
    },
    yAxis: {
      type: 'category',
      data: topDevices.map(device => device.name),
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 10
      }
    },
    series: [
      {
        name: '功率',
        type: 'bar',
        data: topDevices.map(device => device.power),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            {
              offset: 0,
              color: '#0072ff'
            },
            {
              offset: 1,
              color: '#00eaff'
            }
          ])
        },
        barWidth: '60%'
      }
    ]
  };
  
  deviceRankingChart.setOption(option);
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  deviceRankingChart && deviceRankingChart.resize()
}

onMounted(() => {
  initDeviceRanking()
  
  // 添加窗口大小改变事件
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小改变事件
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  deviceRankingChart && deviceRankingChart.dispose()
})
</script>

<template>
  <dv-border-box-4 class="dashboard-panel">
    <div class="panel-header" style="margin-left: 40px">设备功率排名</div>
    <div class="chart-container ranking-chart" ref="deviceRankingRef"></div>
  </dv-border-box-4>
</template>

<style scoped>
.dashboard-panel {
  position: relative;
  min-height: 300px; /* 设置最小高度 */
  height: 300px; /* 固定高度 */
  flex: 0 0 auto; /* 禁止收缩 */
  overflow: visible; /* 允许内容超出 */
}

.ranking-chart {
  height: 85%;
  margin-top: 5px;
  padding-bottom: 10px;
}

.panel-header {
  flex-shrink: 0;
  margin-bottom: 8px;
}
</style> 